/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "fdcan.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "string.h"
#include "CAN_Signals.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define ADC_BUFFER_SIZE_ADC1 3		//采集的通道数量
#define ADC_BUFFER_SIZE_ADC2 4
#define ADC_SAMPLE_INTERVAL_MS 10		//采样间隔(ms)
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
volatile uint32_t send_current_time = 0;
volatile uint32_t send_last_time = 0;
volatile uint16_t adcBuffer_adc1[ADC_BUFFER_SIZE_ADC1] = {0}; //DMA把ADC结果保存在这
volatile uint16_t adcBuffer_adc2[ADC_BUFFER_SIZE_ADC2] = {0};	
volatile bool adcConversionComplete_adc1 = {0};			//转换完成标志,需要在main.h中添加include stdbool.h
volatile bool adcConversionComplete_adc2 = {0};	
volatile uint16_t adcData_adc1[ADC_BUFFER_SIZE_ADC1] = {0};
volatile uint16_t adcData_adc2[ADC_BUFFER_SIZE_ADC2] = {0};
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
//自定义CAN1&2 RXFIFO0中断回调函数
void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hcan, uint32_t RxFifo0ITs) {
    FDCAN_RxHeaderTypeDef rx_header;
    uint8_t rx_data[8];
    
    if (HAL_FDCAN_GetRxMessage(hcan, FDCAN_RX_FIFO0, &rx_header, rx_data) == HAL_OK)
			{
        CanFrameType frame_type = (rx_header.IdType == FDCAN_EXTENDED_ID) ? 
                                 CAN_FRAME_EXTENDED : CAN_FRAME_STANDARD;
			//区分can1 can2
			if (hcan->Instance == FDCAN1)
			{
				parse_can1_received_frame(rx_header.Identifier, rx_data, frame_type);
			}
			else
			{
				parse_can2_received_frame(rx_header.Identifier, rx_data, frame_type);
			}
    }
}
// CAN1消息专用json发送函数
void mqtt_send_can1(CanMessage *msg) {
    // 检查输入参数有效性
    if (msg == NULL || msg->len == 0 || msg->len > 8) {
        return;
    }
    
    
    char json_buf[180];
    char hex_buf[17] = {0};
    
    
    // 将数据转换为十六进制字符串，不足8字节的部分填充00
    for(int i = 0; i < 8; i++) {  // 固定循环8次
        // 对于超出实际长度的部分，填充00
        uint8_t byte_data = (i < msg->len) ? msg->data[i] : 0x00;
        sprintf(&hex_buf[i*2], "%02x", byte_data);  // 小写16进制
    }
    
    // 确定CAN1帧类型
    CanFrameType frame_type = CAN_FRAME_STANDARD;
    for (int i = 0; i < can1_frame_count; i++) {
        if (can1_frame_defs[i].can_id == msg->id) {
            frame_type = can1_frame_defs[i].frame_type;
            break;
        }
    }
    
    
    int json_len;
    if (frame_type == CAN_FRAME_EXTENDED) {
        json_len = snprintf(json_buf, sizeof(json_buf),
                         "{\"id\":\"0x%08lX\",\"data\":\"%s\"}",
                         (unsigned long)msg->id, hex_buf);
    } else {
        json_len = snprintf(json_buf, sizeof(json_buf),
                         "{\"id\":\"0x%03lX\",\"data\":\"%s\"}",
                         (unsigned long)msg->id, hex_buf);
    }
    
    // 检查缓冲区并发送
    if (json_len > 0 && json_len < sizeof(json_buf)) {
        HAL_UART_Transmit(&huart2, (uint8_t*)json_buf, strlen(json_buf), HAL_MAX_DELAY);
		}
}
    
void mqtt_send_can2(CanMessage *msg, uint8_t can_bus) {
    // 检查输入参数有效性
    if (msg == NULL || msg->len > 8 || (can_bus != 1 && can_bus != 2)) {
        return; // 无效参数，直接返回
    }
    
    // 创建JSON缓冲区
    char json_buf[150];
    char hex_buf[17] = {0};  // 8字节数据对应16字符+null
    
    // 将数据转换为十六进制字符串，不足8字节的部分填充00
    for(int i = 0; i < 8; i++) {  // 固定循环8次
        // 对于超出实际长度的部分，填充00
        uint8_t byte_data = (i < msg->len) ? msg->data[i] : 0x00;
        sprintf(&hex_buf[i*2], "%02x", byte_data);  // 小写16进制
    }
    
    // 查找对应的帧定义以确定帧类型
    CanFrameType frame_type = CAN_FRAME_STANDARD;
    if (can_bus == 1) {
        for (int i = 0; i < can1_frame_count; i++) {
            if (can1_frame_defs[i].can_id == msg->id) {
                frame_type = can1_frame_defs[i].frame_type;
                break;
            }
        }
    } else { 
        for (int i = 0; i < can2_frame_count; i++) {
            if (can2_frame_defs[i].can_id == msg->id) {
                frame_type = can2_frame_defs[i].frame_type;
                break;
            }
        }
    }
    
    // 构建JSON字符串，包含CANID和数据
    int json_len;
    if (frame_type == CAN_FRAME_EXTENDED) {
        json_len = snprintf(json_buf, sizeof(json_buf),
                         "{\"id\":\"0x%08lX\",\"data\":\"%s\"}",
                         (unsigned long)msg->id, hex_buf);
    } else {
        json_len = snprintf(json_buf, sizeof(json_buf),
                         "{\"id\":\"0x%03lX\",\"data\":\"%s\"}",
                         (unsigned long)msg->id, hex_buf);
    }
    
    // 检查JSON是否溢出
    if (json_len > 0 && json_len < sizeof(json_buf)) {
        HAL_UART_Transmit(&huart2, (uint8_t*)json_buf, strlen(json_buf), HAL_MAX_DELAY);
		}
    
    
}
//adc DMA转换完成回调函数
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef*hadc)
{
	if(hadc->Instance == ADC1){
	adcConversionComplete_adc1 = true;
	} else {
	adcConversionComplete_adc2 = true;	
	}
}
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  MX_FDCAN1_Init();
  MX_FDCAN2_Init();
  MX_FDCAN3_Init();
  MX_ADC1_Init();
  MX_ADC2_Init();
  MX_SPI3_Init();
  MX_TIM2_Init();
  MX_TIM3_Init();
  MX_TIM5_Init();
  MX_TIM20_Init();
  /* USER CODE BEGIN 2 */
	//初始化定时器tim2,3,5,20
	HAL_TIM_Base_Start(&htim2);
	HAL_TIM_Base_Start(&htim3);
	HAL_TIM_Base_Start(&htim5);
	HAL_TIM_Base_Start(&htim20);
	//启动can rx fifo0,启用硬件中断
	if (HAL_FDCAN_Start(&hfdcan1) != HAL_OK){
		Error_Handler();
	}
	if (HAL_FDCAN_Start(&hfdcan2) != HAL_OK){
		Error_Handler();
	}
	init_can1_frame_callbacks();
	init_can2_frame_callbacks();
	init_can1_frames();
	init_can2_frames();
	config_can1_filters(&hfdcan1);
	config_can2_filters(&hfdcan2);		//can2 config
	//启动adc dma采集
	if (HAL_ADC_Start_DMA(&hadc1, (uint32_t*)adcBuffer_adc1, ADC_BUFFER_SIZE_ADC1) != HAL_OK)
	{
		Error_Handler();
	}
	if (HAL_ADC_Start_DMA(&hadc2, (uint32_t*)adcBuffer_adc2, ADC_BUFFER_SIZE_ADC2) != HAL_OK)
	{
		Error_Handler();
	}
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		send_current_time = HAL_GetTick();
    
    // 每100ms发送周期
    if (send_current_time - send_last_time >= 100)
    {
        send_last_time = send_current_time;
        
        /* 发送所有CAN1报文 */
        for (int i = 0; i < can1_frame_count; i++) {
            CanMessage msg = {
                .id = can1_frame_defs[i].can_id,
                .len = 8,
            };
            memcpy(msg.data, can1_frame_defs[i].data, 8);
            mqtt_send_can1(&msg);
        }
        
        /* 发送所有CAN2报文 */
        for (int i = 0; i < can2_frame_count; i++) {
            CanMessage msg = {
                .id = can2_frame_defs[i].can_id,
                .len = 8,
            };
            memcpy(msg.data, can2_frame_defs[i].data, 8);
            mqtt_send_can2(&msg, 2);
        }
				//加入adc发送，在这里处理adc数据
				if (adcConversionComplete_adc1)
				{
					adcConversionComplete_adc1 = false;
					for (int i = 0; i < ADC_BUFFER_SIZE_ADC1; i++)
					{
						adcData_adc1[i] = adcBuffer_adc1[i];
					}
					//HAL_UART_Transmit(&huart2, adcData_adc1, sizeof(adcData_adc1), HAL_MAX_DELAY);
					//之后将adc值转换为物理值再通过串口发送
				}
				else
				{
					printf("ADC1 Conv unfinished\n");
				}
				HAL_Delay(1);
				if (adcConversionComplete_adc2)
				{
					adcConversionComplete_adc2 = false;
					for (int i = 0; i < ADC_BUFFER_SIZE_ADC2; i++)
					{
						adcData_adc2[i] = adcBuffer_adc2[i];
					}
					//HAL_UART_Transmit(&huart2, adcData_adc2, sizeof(adcData_adc2), HAL_MAX_DELAY);
					//之后将adc值转换为物理值再通过串口发送
				}
				else
				{
					printf("ADC2 Conv unfinished\n");
				}
				
				HAL_Delay(1);
				
				//此处补充发送轮速代码
					
			
    }
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
  RCC_OscInitStruct.PLL.PLLN = 85;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
